//
//  RootViewController.m
//  WDFans
//
//  Created by Zhihong Yuan on 2/3/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "RootViewController.h"
#import "LoginViewController.h"
#import "ZHDataService.h"
#import "ForwardWeiboViewController.h"
#import "ActivityViewManager.h"
#import "WDFansAppDelegate.h"



@interface RootViewController()

@property (nonatomic, copy) NSString *weiboText;
    
@end

@implementation RootViewController

@synthesize weiboText;

#pragma mark - weibo methods

- (void)openAuthenticateView {
	[[ZHDataService sharedService] removeCachedOAuthDataForUsername];
	[[ZHDataService sharedService].engine signOut];
	UIViewController *controller = [OAuthController controllerToEnterCredentialsWithEngine:[ZHDataService sharedService].engine delegate: self];
	if (controller) 
		[self presentModalViewController: controller animated: YES];
}

- (void)postStatusDidSucceed:(WeiboClient*)sender obj:(NSObject*)obj;
{
    //[self openAuthenticateView];
    if (sender.hasError) {
		[sender alert];
        if (sender.statusCode == 401) {
            [self openAuthenticateView];
        }
    }
    else
    {
        [ActivityViewManager showErrorViewWithMessage:@"微博发布成功"];
        [self dismissModalViewControllerAnimated:YES];
    }
}

- (void)loadData {
	if (nil != weiboClient) { 
		[weiboClient release];
        weiboClient = nil;
	}
    
    if(nil == self.weiboText || [self.weiboText isEqualToString:@""])
    {
        [ActivityViewManager showErrorViewWithMessage:@"微博绑定成功"];
        return;
    }
    else
    {
        WeiboClient *client = [[WeiboClient alloc] initWithTarget:self 
                                                       engine:[ZHDataService sharedService].engine
                                                       action:@selector(postStatusDidSucceed:obj:)];

        [client post:self.weiboText];
    }
}

- (void)loadTimeline {
	UIViewController *controller = [OAuthController controllerToEnterCredentialsWithEngine:[ZHDataService sharedService].engine delegate: self];
	
	if (controller)
    {
        [self dismissModalViewControllerAnimated:NO];
		[self presentModalViewController: controller animated: YES];
    }
	else {
		[self loadData];
	}
}

#pragma mark - Ryan methods
- (void)sendWeibo:(NSNotification *)notification
{
    NSLog(@"send weibo ...");
    NSDictionary *userInfo = [notification userInfo];
    self.weiboText = [userInfo objectForKey:@"text"];
    [self loadTimeline];
}

#pragma mark - View lifecycle
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [weiboText release];
    [weiboClient release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"%@",[[UIDevice currentDevice] systemVersion]);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendWeibo:) name:kPostWeiBoNotification object:nil];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark OAuthSinaWeiboControllerDelegate
- (void) OAuthController: (OAuthController *) controller authenticatedWithUsername: (NSString *) username {
	[self loadTimeline];
}

- (void) OAuthControllerFailed: (OAuthController *) controller {
	if (controller) 
		[self presentModalViewController: controller animated: YES];
	
}

- (void) OAuthControllerCanceled: (OAuthController *) controller {
    [ActivityViewManager showErrorViewWithMessage:@"取消绑定微博"];
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    //新闻
    if (![item.title isEqualToString:@"新闻"]) {
        WDFansAppDelegate *appDelegate = (WDFansAppDelegate *)[UIApplication sharedApplication].delegate;
        NSArray* array = appDelegate.rootController.viewControllers;
        if ([array count]>0) {
            UINavigationController* vc = [array objectAtIndex:0];
            vc.tabBarItem.badgeValue = nil;
        }
    }
    
}

@end
